import { get, post } from './axios'
import type { ApiResponse } from '@/model/common-model'

/**
 * 登录参数接口
 */
export interface LoginParams {
  login_name?: string
  username?: string // 兼容username参数
  password: string
}

/**
 * 注册参数接口
 */
export interface RegisterParams {
  login_name: string
  full_name: string
  password: string
  confirm_password: string
  department?: string
}

/**
 * 用户信息接口
 */
export interface UserInfo {
  id: number
  login_name: string
  full_name: string
  role_id: number
  role_name?: string
  department?: string
  status: number
}

/**
 * 登录响应接口
 */
export interface LoginResponse {
  access_token: string
  token_type: string
  user: UserInfo
}

/**
 * 角色信息接口
 */
export interface RoleInfo {
  id: number
  name: string
  description: string
  created_at: string
  updated_at: string
}

/**
 * 用户登录
 * @param data 登录参数
 * @returns Promise
 */
export function login(data: LoginParams): Promise<ApiResponse<LoginResponse>> {
  // 处理兼容问题，如果提供了username但没有login_name，将username复制到login_name
  const payload = { ...data };
  if (payload.username && !payload.login_name) {
    payload.login_name = payload.username;
  }
  return post<LoginResponse>('/auth/login', payload);
}

/**
 * 用户注册
 * @param data 注册参数
 * @returns Promise
 */
export function register(data: RegisterParams): Promise<ApiResponse<UserInfo>> {
  console.log('Register data being sent:', JSON.stringify(data))
  
  // 确保只发送必要的字段，不包含多余的字段
  const payload = {
    login_name: data.login_name,
    full_name: data.full_name,
    password: data.password,
    confirm_password: data.confirm_password, // 确保这个字段被包含
    department: data.department
  }
  
  console.log('Cleaned register payload:', JSON.stringify(payload))
  return post<UserInfo>('/auth/register', payload)
}


/**
 * 获取用户信息
 * @param userId 用户ID
 * @returns Promise
 */
export function getUserById(userId: number): Promise<ApiResponse<UserInfo>> {
  return get<UserInfo>(`/users/${userId}`)
}


/**
 * 退出登录
 * @returns Promise
 */
export function logout(): Promise<ApiResponse<{ message: string }>> {
  return post<{ message: string }>('/auth/logout', {})
}

/**
 * 获取当前用户的菜单权限
 * @returns Promise
 */
export function getUserMenuPermissions(): Promise<ApiResponse<any>> {
  // 使用正确的API路径，可能后端期望使用不同的路径
  // 根据错误提示，改用角色菜单权限接口
  return get('/auth/menu-permissions')
}
